package com.qf.security.service;

/*
 *  @author Administrator
 *  @version V1.0
 *  @Project banwoqiche
 *  @Package com.qf.security.service
 *  @Description
 *  @Date2022/3/29 0029 16:10
 */

import com.qf.bean.SysUser;
import com.qf.mapper.UserMapper;
import com.qf.security.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class MyUserSetailService implements UserDetailsService {
    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //username,我们登陆的时候传递过来的用户名
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userMapper.findByUsername(username);
        //如果用户不存在
        if (user == null) {
            throw new UsernameNotFoundException("用户名密码不存在");
        }
        if (user.getStatus() == 0) {
            throw new AccountExpiredException("zhanghao guo qi");
        }
        if (user.getStatus() == 2) {
            throw new LockedException("账号被封禁");
        }
        //参数1, 用户名,就是当前的用户名
        //参数2 数据库中查询到的密码
        //参数3 用户有的权限,可以后面再查询一样,可以在之类先查询,设置进去, 也可以后面更新,但是我个人建议先写个空的
        //因为可能账号密码不对,你要获取权限需要查询数据库, 就白查询了
        // return new org.springframework.security.core.userdetails.User(username, user.getPassword(), new ArrayList<>());
        // 如果一个类本身的功能不足以满足我们的需求的时候可以通过继承扩展

        return new BaseUser(username,user.getPassword(),new ArrayList<>(),user.getUserId());
    }
}
